feature.load("file");
feature.load("shell");

var java = feature.create(function () {

    var javaHome = shell.env()["JAVA_HOME"];
    if (!javaHome) {
        console.err("JAVA_HOME not set");
    }
    var javaBin = file(javaHome, "bin");
    var javaExe = file(javaBin, "java");
    var javacExe = file(javaBin, "javac");

    function compile(classpathSets, sourceSets, destination /*, options */) {
        classpathSets = [].concat(classpathSets);
        sourceSets = [].concat(sourceSets);
        var classpaths = [];
        classpathSets.forEach(function(fileSet) {
            classpaths = classpaths.concat(fileSet.files());
        });
        var sourcepaths = [];
        var sourcefiles = [];
        sourceSets.forEach(function(fileSet) {
            sourcepaths.push(fileSet.dir());
            sourcefiles = sourcefiles.concat(fileSet.files().map(Files.path()));
        });
        var commands = [
            javacExe.path(),
            "-classpath", Files.join.apply(this, classpaths),
            "-sourcepath", Files.join.apply(this, sourcepaths),
            "-d", destination.path()
        ].concat(sourcefiles);
        console.log.apply(this, commands);
        return shell.exec(commands, null, global.baseDir);
    }

    function exec(args) {
        console.log(javaExe);
        return shell.exec(javaExe);
    }

    return {
        compile: compile,
        exec: exec
    };
});
